package com.cch.demo.sys.controller;

import cn.hutool.core.date.DateUtil;
import com.cch.demo.sys.util.AppFileUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("file")
public class FileContoller {

    @RequestMapping("uploadFile")
    public Map<String,Object> uploadFile(MultipartFile mf){
        //获取文件名
        String oldname = mf.getOriginalFilename();
        //根据文件名生成新的文件名
        String newname = AppFileUtils.creatNewFileName(oldname);

        //得到当前日期字符串
        String dirname = DateUtil.format(new Date(),"yyyy-MM-dd");
        //创建文件夹
        File dirFile = new File(AppFileUtils.UPLOAD_PATH,dirname);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }

        //构造文件对象
        File file = new File(dirFile,newname+"_temp");
        //将mf读入到file中
        try {
            mf.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String,Object> map = new HashMap<>();
        map.put("path",dirname+"/"+newname+"_temp");
        return map;
    }

    /**
     * 图片显示
     */
    @RequestMapping("showImageByPath")
    public ResponseEntity<Object> showImageByPath(String path){
        return AppFileUtils.createResponseEntity(path);
    }
}
